const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.get('/get-news', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  const { id, sqltype, page_index, page_size } = req.query
  if (
    !Bee.StringUtils.isNotBlank(sqltype) ||
    !Bee.StringUtils.isNotBlank(id) ||
    !Bee.StringUtils.isNumber(page_index * 1) ||
    !Bee.StringUtils.isNumber(page_size * 1)
  )
    return handleError(10003, '参数错误')

  // sqltype: 0 = 默认：升序  1 = 降序
  let sql = ''
  let totalSql = `SELECT count(*) FROM news n LEFT JOIN class c ON n.classid = c.id WHERE n.classid IN (?) ${
    Bee.StringUtils.getStrLast(sqltype, 2) === '0'
      ? 'AND status = 1'
      : Bee.StringUtils.getStrLast(sqltype, 2) === '1'
      ? 'AND status = 2'
      : ''
  } ORDER BY n.created_time ASC`
  if (Bee.StringUtils.getStrLast(sqltype, 1) === '0') {
    sql = `SELECT n.id, n.title, n.classid, c.title class_title, n.created_time, n.updated_time, n.news_type, n.intro, n.cover, n.content, n.tags, n.files, n.img, n.comment_count, n.hits, n.like_count FROM news n LEFT JOIN class c ON n.classid = c.id WHERE n.classid IN (?) ${
      Bee.StringUtils.getStrLast(sqltype, 2) === '0'
        ? 'AND status = 1'
        : Bee.StringUtils.getStrLast(sqltype, 2) === '1'
        ? 'AND status = 2'
        : ''
    } ORDER BY n.created_time ASC LIMIT ?,?`
  } else if (Bee.StringUtils.getStrLast(sqltype, 1) === '1') {
    sql = `SELECT n.id, n.title, n.classid, c.title class_title, n.created_time, n.updated_time, n.news_type, n.intro, n.cover, n.content, n.tags, n.files, n.img, n.comment_count, n.hits, n.like_count FROM news n LEFT JOIN class c ON n.classid = c.id WHERE n.classid IN (?) ${
      Bee.StringUtils.getStrLast(sqltype, 2) === '0'
        ? 'AND status = 1'
        : Bee.StringUtils.getStrLast(sqltype, 2) === '1'
        ? 'AND status = 2'
        : ''
    } ORDER BY n.created_time DESC LIMIT ?,?`
  }

  // 获取数据总条数
  const [getTotalError, getTotalSuccess] = await to(db.query(totalSql, [id]))
  if (getTotalError || !getTotalSuccess) return handleError(-1, getTotalError)
  const total = getTotalSuccess[0]['count(*)'] // 数据总条数

  const [getNewsError, getNewsSuccess] = await to(
    db.query(sql, [
      id.split(','), // 以 ，转数组
      (parseInt(page_index) - 1) * parseInt(page_size),
      parseInt(page_size),
    ])
  )
  if (getNewsError || !getNewsSuccess) return handleError(-1, getNewsError)
  return resp.json({
    code: 0,
    msg: status_code[0],
    data: {
      list: getNewsSuccess,
      total: total,
    },
  })
})

module.exports = router
